<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 	购物车管理
 * @package app\erp\model
 */
class Salecarlogic{

    /**
     * 首页
	 * @param store_id 	 int 门店id
     * @author  shiqiang
     * @return array_out(code, message, data)
     */
    public function salecar_list($user_id, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'store_id' 	=> $store_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
			// 检测已经取消当前用户的订单，并释放库存
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$list 			= model('ErpGoodsSalecar') -> where('uid', $user_id) -> order('create_time desc') -> select(); //购物车商品
			// $warehouse_id 	= model('ErpStoreWarehouse') -> where('store_id', $store_id) -> order('create_time desc') -> column('warehouse_id');//门店下仓库
			
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$warehouse_zong = model('ErpWarehouse') -> where('type', 2) -> column('id');//总仓
			
			$rel_list = [];
			if(!empty($list)){
				foreach($list as $key => $value){
					$goods_id 	= $value['goods_id'];
					$sku_id 	= $value['sku_id'];
					
					$map = [
						['goods_id', '=', $goods_id],
						['sku_id', '=', $sku_id],
						['warehouse_id', 'in', $store_warehouse_list[0]],
					];
					$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('sum(available_num) as available_num,min(price) as price')->where($map)->find();//库存 / 价格信息
					if($goods_stock['price'] == ''){
						$map = [
							['goods_id', '=', $goods_id],
							['sku_id', '=', $sku_id],
							['warehouse_id', 'in', $warehouse_zong],
						];
						$goods_stock = model('ErpGoodsWarehouseStockNum') ->field('min(price) as price')->where($map)->find();//库存 / 价格信息
						$goods_stock['available_num'] = 0;
					}
                    $goods_sku = controller('GoodsSkulogic', 'logic') -> goods_sku_info_skuid($user_id, $sku_id, $store_id);//商品详情
                    //dump($goods_sku);
					if($goods_sku['code'] != 200) continue;
					
					$rel_list[] = [
                        'id' 	        => $value['id'], //要改成sku的图片
						'goodsSkuInfo' 	=> $goods_sku['data'], //要改成sku的图片
						'num' 			=> $value['num'],
						'availableNum' 	=> $goods_stock['available_num'] == '' ? 0 : $goods_stock['available_num'],
						'price' 		=> $goods_stock['price'] == '' ? $goods_sku['data']['price'] : $goods_stock['price'],
					];
				}
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 添加
     * @param goods_id 	 int 商品id
     * @param sku_id 	 int sku_id
     * @param num 	     int 数量
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function add($user_id, $goods_id, $sku_id, $num, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'goods_id'  => $goods_id,
				'sku_id' 	=> $sku_id,
				'num'       => $num,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$map = [];
			$map['uid'] 	 = $user_id;
			$map['goods_id'] = $goods_id;
			$map['sku_id']   = $sku_id;
			$car_info = model('ErpGoodsSalecar') -> where($map) -> find(); //当前购物车数量

            //查库存  超过则不执行购物车添加
            //根据门店id 查询出仓库的id
            $store_warehouse_list = [];
            $warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
            foreach ($warehouse_list['data'] as $key => $value) {
                if($value['type'] == 1){//分店仓库
                    $store_warehouse_list[] = $value['wid'];
                }
            }
            $map = [
                ['goods_id', '=', $goods_id],
                ['warehouse_id', 'in', $store_warehouse_list],
                ['sku_id', '=', $sku_id],
            ];
            $goods_stock = model('ErpGoodsWarehouseStockNum') ->field('sum(available_num) as available_num') -> where($map) -> find();//库存价格信息
            if(intval($goods_stock['available_num']) == 0){
                DB::rollback();
                return array_out(-1006, '该商品无货！');//添加失败 返回-1005,error
            }

            $car_info_num = intval(isset($car_info['num'])?$car_info['num']:0);
      
            if(( $car_info_num + $num ) > intval($goods_stock['available_num'])){
                DB::rollback();
                return array_out(-1006, '购物车数量已满，无法加入购物车');//添加失败 返回-1005,error
            }

			if(!empty($car_info)){
				$num += $car_info['num'];//增加
				$rel = controller('Salecarlogic', 'logic') -> update_sku_num($user_id, $car_info['id'], $num);//变更数量
			}else{
				$rel = model('ErpGoodsSalecar') -> addData($user_id,$goods_id, $sku_id, $num);//添加
			}
            if($rel['code'] < 0){
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 添加 - 扫码
     * @param article_no 	 int 条码
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function add_scan($user_id, $article_no, $num = 1, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	 => $user_id,
				'article_no' => $article_no,
				'num' 		 => $num,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$map = [];
			$map['article_no'] = $article_no;
			$sku_info = model('ErpGoodsSku') -> where($map) -> find(); //当前购物车数量
            //dump($sku_info);
			if(!$sku_info){
				DB::rollback();
                return array_out(-1005, '暂无该商品信息');//后置错误 -1003
			}
			
			$goods_id = $sku_info['goods_id'];
			$sku_id   = $sku_info['id'];
			
            $rel = controller('Salecarlogic', 'logic') -> add($user_id, $goods_id, $sku_id, $num,$store_id);//加入购物车
            //dump($rel);
            if($rel['code'] < 0){
                DB::rollback();
                return array_out(-1005, $rel['message']);//添加失败 返回-1005,error
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 编辑数量
     * @param id  int  购物车id
     * @param num int  数量
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function update_sku_num($user_id, $id, $num){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
                'num'     	=> $num,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$rel = model('ErpGoodsSalecar') -> updateSkuNum($id, $num);
            if($rel['code'] < 0){
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 编辑sku_id
     * @param id  int  购物车id
     * @param goods_id int  商品id
     * @param sku_id int    skuid
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function update_sku_id($user_id, $id, $goods_id, $sku_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
                'goods_id'  => $goods_id,
                'sku_id'  	=> $sku_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$rel = model('ErpGoodsSalecar') -> updateSkuId($id, $goods_id, $sku_id);
            if($rel['code'] < 0){
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 删除
     * @param array $id
     * @author shiqiang
     * @return bool
     */
    public function delete($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$rel = model('ErpGoodsSalecar') -> deleteData($id);
			if($rel['code'] < 0){
				return array_out(-1005, 'error');//删除失败 返回-1005,error
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}